package com.example.testspringwebflux;

import com.example.testspringwebflux.bean.SimpleConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@Import(SimpleConfiguration.class)
@Slf4j
public class TestSpringWebfluxApplication {

    public class MvcConfig implements WebMvcConfigurer {

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TestSpringWebfluxApplication.class, args);
    }

    @RestController
    @RequestMapping("/test")
    public class Test {

        @CrossOrigin("*")
        @RequestMapping(value = "/helloworld", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public SseEmitter helloworld() {
            SseEmitter sseEmitter = new SseEmitter(30000L);
            CompletableFuture.runAsync(()-> {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    try {
                        sseEmitter.send(format);
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                try {
                    sseEmitter.send(SseEmitter.event().name("end").data("end").build());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
                sseEmitter.complete();
            });
            sseEmitter.onCompletion(()-> System.out.println("处理完成"));
            return sseEmitter;
        }
    }
}
